#include "FieldBuilder.h"

#include "ScriptCompiler/ScriptFileContext.h"
#include "ScriptCompiler/ASTBuilder/ExpressionBuilder.h"


CGSharpFieldBuilder::CGSharpFieldBuilder(std::shared_ptr<CScriptFileContext> InContext)
{
    Context = InContext;
    Result= std::make_shared<CGSharpFieldNode>(Context);
}

bool CGSharpFieldBuilder::ReadCurentToken()
{


    auto Token = Context->GetCurrentToken();

    if (Token->Type == EScriptTokenType::Identifier)
    {
        Result->Name = Token;
        Context->CurrentTokenIndex++;

        auto NextToken = Context->GetCurrentToken();
        if (NextToken->Type == EScriptTokenType::Semicolon)
        {
            //skip semicolon
            Context->CurrentTokenIndex++;
            return true;
        }
        else if(NextToken->Type == EScriptTokenType::Assign)
        {
            //find end ';'
            auto SemiColon = FindNextToken(EScriptTokenType::Semicolon,Context);
            if(!SemiColon)
            {
                Context->RaiseError(10042,Context->GetCurrentToken(),U"Expected ';' at end of field declaration");
                return false;
            }

            //skip '='
            Context->CurrentTokenIndex ++ ;
            
            auto ExpressionBuilder =std::make_shared<CExpressionBuilder>(Context,SemiColon.GetValue());
            
            if(!ExpressionBuilder->ReadCurentToken())
            {
                return false;
            }

            Result->Assignment = ExpressionBuilder ->Result;

            //skip semicolon
            {
                auto NextToken = Context->GetCurrentToken();
                if (NextToken->Type != EScriptTokenType::Semicolon)
                {
                    Context->RaiseError(10043,NextToken,U"Expected semicolon after field assignment");
                    return false;
                }

                Context->CurrentTokenIndex++;
            }

            return true;
        }
        else
        {
            Context->RaiseError(10044,NextToken,U"Expected semicolon after field name");
            return false;
        }
    }
    else
    {
        Context->RaiseError(10045,Token,U"Expected field name");
        return false;
    }
}
